package www.com.library.view;

import android.text.TextPaint;

/**
 * 根据text自动绘制调整视图大小
 * 
 * @author Administrator
 *
 */
public class UIAutoScaleTextUtil {
	public static class AutoScaledSize {
		public float mTextSize;
		public float mTextScaleX;
		public float mMeasuredWidth;
	}

	private static final float MIN_ACCEPTABLE_TEXT_SIZE = 12;
	private static final float MIN_ACCEPTABLE_TEXT_WIDTH_DIFF = 2.0f;

	private float mMinTextSize = MIN_ACCEPTABLE_TEXT_SIZE;
	private float mMaxTextSize;
	private float mTextScaleX;
	private AutoScaledSize mScaledSize = new AutoScaledSize();

	/**
	 * 设置显示文字的最小size
	 */
	public void setMinTextSize(float minTextSize) {
		mMinTextSize = minTextSize;
	}

	/**
	 * 设置显示文字的最大size
	 */
	public void setMaxTextSize(float maxTextSize) {
		mMaxTextSize = maxTextSize;
	}

	/**
	 * 设置显示文字的比例
	 */
	public void setTextScaleX(float scaleX) {
		mTextScaleX = scaleX;
	}

	/**
	 * 根据text自动绘制调整视图大小
	 */
	public AutoScaledSize rescaleText(CharSequence text, TextPaint paint,
			float drawableWidth) {
		if (text != null && paint != null && mMaxTextSize > 0) {
			/* Adjust scale to fit the rect */
			if (drawableWidth <= 0)
				return null;

			final int textLen = text.length();
			float textSize = mMaxTextSize;
			float textScaleX = mTextScaleX;

			paint.setTextSize(textSize);
			paint.setTextScaleX(textScaleX);
			float width = paint.measureText(text, 0, textLen);
			if (width > drawableWidth) {
				float textStep = textSize / 2;
				float widthDiff = Math.abs(drawableWidth - width);
				while (widthDiff > MIN_ACCEPTABLE_TEXT_WIDTH_DIFF
						|| width > drawableWidth) {
					if (width < drawableWidth && textStep < 1)
						break;
					else if (width > drawableWidth)
						textSize -= textStep;
					else if (width < drawableWidth)
						textSize += textStep;
					else
						break;

					if (textStep >= 1)
						textStep = textStep / 2;
					paint.setTextSize(textSize);
					width = paint.measureText(text, 0, textLen);
					widthDiff = Math.abs(drawableWidth - width);
				}

				if (textSize < mMinTextSize)
					textSize = mMinTextSize;

				float scaleXStep = 0.05f;
				while (width > drawableWidth) {
					textScaleX -= scaleXStep;
					if (textScaleX < 0.5f)
						break;
					paint.setTextScaleX(textScaleX);
					width = paint.measureText(text, 0, textLen);
				}

				mScaledSize.mTextSize = textSize;
				mScaledSize.mTextScaleX = textScaleX;
				mScaledSize.mMeasuredWidth = width;
			} else {
				mScaledSize.mTextSize = mMaxTextSize;
				mScaledSize.mTextScaleX = mTextScaleX;
				mScaledSize.mMeasuredWidth = width;
			}

			return mScaledSize;
		}

		/* No scale process is taken */
		return null;
	}
}
